import React, { useState } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Grid,
  Card,
  CardContent,
  Divider,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  Stack,
  Snackbar,
  useTheme,
  alpha,
  Fade,
  Paper,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';

interface WorkExp {
  id: number;
  company: string;
  position: string;
  start_date: string;
  end_date: string | null;
  description: string;
  user_id: number;
}

interface WorkExperienceProps {
  workExperiences: WorkExp[];
  onUpdate: () => void;
}

const formatDate = (dateString: string | null) => {
  if (!dateString) return '至今';
  
  // 假设日期格式为 YYYY-MM-DD
  const parts = dateString.split('-');
  if (parts.length >= 2) {
    return `${parts[0]}年${parts[1]}月`;
  }
  return dateString;
};

const WorkExperience: React.FC<WorkExperienceProps> = ({ workExperiences, onUpdate }) => {
  const theme = useTheme();
  const [open, setOpen] = useState(false);
  const [editingExp, setEditingExp] = useState<WorkExp | null>(null);
  const [formData, setFormData] = useState({
    company: '',
    position: '',
    start_date: '',
    end_date: '',
    description: '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  const resetForm = () => {
    setFormData({
      company: '',
      position: '',
      start_date: '',
      end_date: '',
      description: '',
    });
    setEditingExp(null);
    setError('');
  };

  const handleOpenDialog = (exp?: WorkExp) => {
    if (exp) {
      setEditingExp(exp);
      setFormData({
        company: exp.company,
        position: exp.position,
        start_date: exp.start_date.split('T')[0],
        end_date: exp.end_date ? exp.end_date.split('T')[0] : '',
        description: exp.description,
      });
    } else {
      resetForm();
    }
    setOpen(true);
  };

  const handleCloseDialog = () => {
    setOpen(false);
    resetForm();
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async () => {
    setLoading(true);
    setError('');

    try {
      // 验证表单
      if (!formData.company || !formData.position || !formData.start_date) {
        throw new Error('公司名称、职位和开始日期不能为空');
      }

      // 验证日期格式 (YYYY-MM-DD)
      const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
      if (!dateRegex.test(formData.start_date)) {
        throw new Error('开始日期格式无效，请使用YYYY-MM-DD格式');
      }

      if (formData.end_date && !dateRegex.test(formData.end_date)) {
        throw new Error('结束日期格式无效，请使用YYYY-MM-DD格式');
      }

      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      const payload = {
        ...formData,
        end_date: formData.end_date || null,
      };

      const url = editingExp 
        ? `/api/user/work-experience/${editingExp.id}` 
        : '/api/user/work-experience';

      const method = editingExp ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '保存工作经历失败');
      }

      setSuccessMessage(editingExp ? '工作经历更新成功' : '工作经历添加成功');
      setSuccess(true);
      handleCloseDialog();
      onUpdate(); // 通知父组件更新数据
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    setDeletingId(id);
    setDeleteConfirmOpen(true);
  };

  const confirmDelete = async () => {
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      const response = await fetch(`/api/user/work-experience/${deletingId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || '删除工作经历失败');
      }

      setSuccessMessage('工作经历删除成功');
      setSuccess(true);
      setDeleteConfirmOpen(false);
      onUpdate(); // 通知父组件更新数据
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
      setDeletingId(null);
    }
  };

  return (
    <Box sx={{ py: 2, px: { xs: 2, md: 3 } }}>
      <Snackbar 
        open={success} 
        autoHideDuration={3000} 
        onClose={() => setSuccess(false)} 
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert 
          severity="success" 
          onClose={() => setSuccess(false)}
          sx={{ 
            borderRadius: '12px',
            boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)',
            '& .MuiAlert-icon': {
              alignItems: 'center',
            }
          }}
        >
          {successMessage}
        </Alert>
      </Snackbar>

      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography 
          variant="h5" 
          component="h2"
          sx={{ 
            fontSize: '1.5rem',
            fontWeight: 600,
            color: theme.palette.text.primary,
          }}
        >
          工作经历
        </Typography>
        <Button 
          startIcon={<AddIcon />} 
          variant="contained" 
          color="primary"
          onClick={() => handleOpenDialog()}
          sx={{
            borderRadius: '24px',
            px: 3,
            py: 1,
            boxShadow: '0 4px 12px rgba(25, 118, 210, 0.2)',
            fontWeight: 500,
            transition: 'all 0.2s',
            '&:hover': {
              boxShadow: '0 6px 16px rgba(25, 118, 210, 0.3)',
              transform: 'translateY(-2px)',
            },
          }}
        >
          添加工作经历
        </Button>
      </Box>

      {error && (
        <Alert 
          severity="error" 
          sx={{ 
            mb: 3, 
            borderRadius: '12px',
            '& .MuiAlert-icon': {
              alignItems: 'center',
            }
          }}
        >
          {error}
        </Alert>
      )}

      <Fade in={true} timeout={800}>
        <Box>
          {workExperiences.length === 0 ? (
            <Paper 
              elevation={0}
              sx={{ 
                textAlign: 'center', 
                py: 6, 
                px: 3,
                borderRadius: '16px',
                backgroundColor: alpha(theme.palette.background.default, 0.6),
                border: `1px dashed ${alpha(theme.palette.primary.main, 0.2)}`,
              }}
            >
              <Typography 
                variant="body1" 
                color="textSecondary"
                sx={{
                  mb: 2,
                  fontSize: '1rem',
                }}
              >
                暂无工作经历，点击"添加工作经历"按钮开始添加
              </Typography>
              <Button
                startIcon={<AddIcon />}
                variant="outlined"
                color="primary"
                onClick={() => handleOpenDialog()}
                sx={{
                  borderRadius: '20px',
                  px: 3,
                }}
              >
                添加第一份工作经历
              </Button>
            </Paper>
          ) : (
            <Stack spacing={3}>
              {workExperiences.map((exp) => (
                <Card 
                  key={exp.id} 
                  elevation={0}
                  sx={{ 
                    mb: 0, 
                    borderRadius: '16px',
                    overflow: 'hidden',
                    transition: 'all 0.3s ease',
                    border: `1px solid ${alpha(theme.palette.divider, 0.08)}`,
                    '&:hover': {
                      boxShadow: '0 8px 24px rgba(0, 0, 0, 0.08)',
                      transform: 'translateY(-2px)',
                      borderColor: 'transparent',
                    },
                  }}
                >
                  <CardContent sx={{ p: 3 }}>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                      <Box>
                        <Typography 
                          variant="h6" 
                          component="h3"
                          sx={{
                            fontWeight: 600,
                            fontSize: '1.25rem',
                            color: theme.palette.text.primary,
                            mb: 0.5,
                          }}
                        >
                          {exp.position}
                        </Typography>
                        <Typography 
                          variant="subtitle1" 
                          sx={{
                            color: theme.palette.primary.main,
                            fontWeight: 500,
                            fontSize: '1.05rem',
                            mb: 0.5,
                          }}
                        >
                          {exp.company}
                        </Typography>
                        <Typography 
                          variant="body2" 
                          sx={{
                            color: theme.palette.text.secondary,
                            fontSize: '0.9rem',
                          }}
                        >
                          {formatDate(exp.start_date)} - {formatDate(exp.end_date)}
                        </Typography>
                      </Box>
                      <Box>
                        <IconButton 
                          size="small" 
                          color="primary"
                          onClick={() => handleOpenDialog(exp)}
                          sx={{
                            backgroundColor: alpha(theme.palette.primary.main, 0.08),
                            mr: 1,
                            '&:hover': {
                              backgroundColor: alpha(theme.palette.primary.main, 0.12),
                            },
                          }}
                        >
                          <EditIcon fontSize="small" />
                        </IconButton>
                        <IconButton 
                          size="small" 
                          color="error"
                          onClick={() => handleDelete(exp.id)}
                          sx={{
                            backgroundColor: alpha(theme.palette.error.main, 0.08),
                            '&:hover': {
                              backgroundColor: alpha(theme.palette.error.main, 0.12),
                            },
                          }}
                        >
                          <DeleteIcon fontSize="small" />
                        </IconButton>
                      </Box>
                    </Box>
                    <Divider sx={{ my: 2, borderColor: alpha(theme.palette.divider, 0.1) }} />
                    <Typography 
                      variant="body1" 
                      sx={{ 
                        whiteSpace: 'pre-line',
                        color: theme.palette.text.primary,
                        lineHeight: 1.6,
                      }}
                    >
                      {exp.description}
                    </Typography>
                  </CardContent>
                </Card>
              ))}
            </Stack>
          )}
        </Box>
      </Fade>

      {/* 添加/编辑工作经历对话框 */}
      <Dialog 
        open={open} 
        onClose={handleCloseDialog}
        fullWidth
        maxWidth="md"
        PaperProps={{
          elevation: 2,
          sx: {
            borderRadius: '16px',
            overflow: 'hidden',
          }
        }}
      >
        <DialogTitle
          sx={{
            p: 3,
            bgcolor: theme.palette.primary.main,
            color: 'white',
            fontWeight: 600,
          }}
        >
          {editingExp ? '编辑工作经历' : '添加工作经历'}
        </DialogTitle>
        <DialogContent sx={{ p: 3, mt: 1 }}>
          {error && (
            <Alert 
              severity="error" 
              sx={{ 
                mb: 3, 
                borderRadius: '12px',
                '& .MuiAlert-icon': {
                  alignItems: 'center',
                }
              }}
            >
              {error}
            </Alert>
          )}
          <Grid container spacing={3}>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="公司名称"
                name="company"
                value={formData.company}
                onChange={handleChange}
                required
                variant="outlined"
                InputProps={{
                  sx: {
                    borderRadius: '12px',
                  }
                }}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="职位"
                name="position"
                value={formData.position}
                onChange={handleChange}
                required
                variant="outlined"
                InputProps={{
                  sx: {
                    borderRadius: '12px',
                  }
                }}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="开始日期 (YYYY-MM-DD)"
                name="start_date"
                value={formData.start_date}
                onChange={handleChange}
                placeholder="例如：2023-01-01"
                required
                variant="outlined"
                InputProps={{
                  sx: {
                    borderRadius: '12px',
                  }
                }}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="结束日期 (YYYY-MM-DD，留空表示至今)"
                name="end_date"
                value={formData.end_date}
                onChange={handleChange}
                placeholder="例如：2023-12-31"
                variant="outlined"
                InputProps={{
                  sx: {
                    borderRadius: '12px',
                  }
                }}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="工作描述"
                name="description"
                value={formData.description}
                onChange={handleChange}
                multiline
                rows={6}
                variant="outlined"
                placeholder="请详细描述您的工作职责、成就和项目经验..."
                InputProps={{
                  sx: {
                    borderRadius: '12px',
                  }
                }}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions sx={{ p: 3, pt: 0 }}>
          <Button 
            onClick={handleCloseDialog}
            sx={{
              borderRadius: '10px',
              px: 3,
              color: theme.palette.text.secondary,
              fontWeight: 500,
            }}
          >
            取消
          </Button>
          <Button 
            onClick={handleSubmit} 
            variant="contained" 
            color="primary"
            disabled={loading}
            sx={{
              borderRadius: '10px',
              px: 3,
              fontWeight: 500,
            }}
          >
            {loading ? '保存中...' : '保存'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={() => setDeleteConfirmOpen(false)}
        PaperProps={{
          elevation: 2,
          sx: {
            borderRadius: '16px',
            overflow: 'hidden',
          }
        }}
      >
        <DialogTitle sx={{ p: 3 }}>
          确认删除
        </DialogTitle>
        <DialogContent sx={{ p: 3, pt: 1 }}>
          <Typography sx={{ color: theme.palette.text.primary }}>
            确定要删除此工作经历记录吗？此操作无法撤销。
          </Typography>
        </DialogContent>
        <DialogActions sx={{ p: 3, pt: 0 }}>
          <Button 
            onClick={() => setDeleteConfirmOpen(false)}
            sx={{
              borderRadius: '10px',
              px: 3,
              color: theme.palette.text.secondary,
              fontWeight: 500,
            }}
          >
            取消
          </Button>
          <Button 
            onClick={confirmDelete} 
            color="error" 
            variant="contained"
            disabled={loading}
            sx={{
              borderRadius: '10px',
              px: 3,
              fontWeight: 500,
            }}
          >
            {loading ? '删除中...' : '确认删除'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default WorkExperience; 